﻿using FSM.IBll;
using FSM.Model;
using FSM.Web.Models;
using FSM.Web.Models.Fileter;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace FSM.Web.Controllers.CodeMode
{
    public class CodeModeController : Controller
    {
        #region 模块

        private readonly ITablesBll tablesBll;

        #endregion

        #region 构造函数

        public CodeModeController(ITablesBll tables_bll)
        {
            this.tablesBll = tables_bll;
        }

        #endregion

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ResultExceptionFilter]
        public JsonResult ListDatabases()
        {
            List<Schemas> result = tablesBll.GetDataBases();
            DataResultModel drm = new DataResultModel();
            drm.success = true;
            drm.data = result;
            return new JsonResult(drm);
        }

        [HttpPost]
        [ResultExceptionFilter]
        public JsonResult ListTables(string id)
        {
            List<SchemaTables> result = tablesBll.GetTables(id);
            DataResultModel drm = new DataResultModel();
            drm.success = true;
            drm.data = result;
            return new JsonResult(drm);
        }

        [HttpPost]
        [ResultExceptionFilter]
        public JsonResult ListFields(string database, string table)
        {
            List<TableFields> result = tablesBll.GetFields(database, table);
            DataResultModel drm = new DataResultModel();
            drm.success = true;
            drm.data = result;
            return new JsonResult(drm);
        }

        /// <summary>
        /// 保存对应文件信息
        /// </summary>
        /// <param name="path">文件的保存路径(完整路径)</param>
        /// <param name="content">文件的内容</param>
        /// <param name="file_name">文件的名称</param>
        /// <returns></returns>
        [HttpPost]
        [ResultExceptionFilter]
        public JsonResult SaveFile(string path, string content, string file_name)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filePath = Path.Combine(path, file_name);
            if (System.IO.File.Exists(filePath))
            {
                throw new Exception("文件已存在");
            }
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(HttpUtility.UrlDecode(content));
                fs.Write(buffer);
            }

            DataResultModel drm = new DataResultModel();
            drm.success = true;
            return new JsonResult(drm);
        }
    }
}
